const Oumirai = require('./oumirai')
const middle = require('./middle')
const custom_character = require('../../../LocalData/custom_character_table.json')
const custom_gacha = require('../../../LocalData/custom_gacha.json')
const holy_pressure_data = require('../data/holyPressureData.json')
const custom_gacha_default = require('../data/custom_gacha.json')
const { pinyin } = require('pinyin-pro')
const { replace } = require('lodash')
const fs = require('fs')
const path = require('path')

let om = null

// 新增干员
function createCharacter() {
    let session = middle.sessions.find(p => p.session == `${om.group}_${om.qq}`)
    session.msg = om.msg
    let reg = new RegExp(/^[3-6]{1}$/)
    let msgChain = om.msg.split(' ')
    if (msgChain.length != 2) {
        om.sendSinlgMessage('格式不正确，请重新录入')
        return
    }
    if (msgChain[0].length > 10) {
        om.sendSinlgMessage('代号太长了，请重新录入')
        return
    }
    if (!reg.test(msgChain[1])) {
        om.sendSinlgMessage('星级范围为3-6，请重新录入')
        return
    }
    let charId = `char_${pinyin(msgChain[0], { toneType: 'none' }).replace(' ', '')}`
    // let isUpdate = false
    // 判断是否存在干员
    if (custom_character[charId]) {
        om.sendSinlgMessage('已存在该干员，本次新增将覆盖原干员信息')
        // isUpdate = true
    }
    // 将数据写入本地
    custom_character[charId] = {
        name: msgChain[0],
        rarity: parseInt(msgChain[1]) - 1
    }
    let dir = path.join(__dirname, '../../../LocalData/custom_character_table.json')
    fs.writeFile(dir, JSON.stringify(custom_character), 'utf8', (err) => {
        console.log('干员新增成功')
    })
    // 将新干员添加到卡池中
    setCharTogacha({
        name: msgChain[0],
        rarity: parseInt(msgChain[1]) - 1,
        charId: charId,
        // isUpdate: isUpdate
    })
    // 修改成功清除缓存
    if (middle.sessions.findIndex(p => p.session == `${om.group}_${om.qq}`) != -1) {
        let index = middle.sessions.findIndex(p => p.session == `${om.group}_${om.qq}`)
        middle.sessions.splice(index, 1)
    }
}

// 将干员添加到卡池对应位置
function setCharTogacha(char) {
    let dir = path.join(__dirname, '../../../LocalData/custom_gacha.json')
    // 判断卡池中是否已存在该干员
    if (custom_gacha.find(p => p.gachaPoolId == `CUSTOM_${om.group}`)) {
        let ops = custom_gacha.find(p => p.gachaPoolId == `CUSTOM_${om.group}`).ops
        for (const item of ops) {
            if (item.charIdList.indexOf(char.charId) != -1) {
                let index = item.charIdList.indexOf(char.charId)
                item.charIdList.splice(index, 1)
            }
            if (item.rarityRank == char.rarity) {
                item.charIdList.push(char.charId)
            }
        }
    }
    else {
        // 他妈的傻逼，傻逼文件流，直接存数据库他不香吗，这一块功能废弃了，不要了
        // console.log('开始写入前')
        // console.log(custom_gacha)
        // // 群内还没有专属卡池的需要新增卡池
        // om.sendSinlgMessage('未查询到专属卡池，正在生成本群专属卡池...')
        // custom_gacha_default.gachaPoolId = `CUSTOM_${om.group}`
        // let new_custom_gacha = JSON.parse(JSON.stringify(custom_gacha)) 
        // new_custom_gacha.push(custom_gacha_default)
        // console.log('加入元素后')
        // console.log(new_custom_gacha)
        // setTimeout(() => {
        //     fs.writeFile(dir, JSON.stringify(new_custom_gacha), 'utf8', (err) => {
        //         om.sendSinlgMessage('已生成本群专属卡池')
        //         setCharTogacha(char)
        //     })
        // }, 1000);

        return
    }
    fs.writeFile(dir, JSON.stringify(custom_gacha), 'utf8', (err) => {
        om.sendSinlgMessage('干员新增成功，并已将新干员添加到专属卡池中')
    })
}
let interTimer = null
// 明日方舟剧情模块
function akLoadPlot() {
    let dialogueItem = middle.dialogueStorage.find(p => p.group == om.group)
    if (!dialogueItem) {
        om.sendSinlgMessage('剧情出错，请重试！')
        clearSession()
        return
    }
    if (dialogueItem.isAuto) {

        switch (parseInt(om.msg)) {
            case 1:
                let dialogue = dialogueItem.dialogue
                if (dialogue && dialogue instanceof Array && dialogue.length > 0) {
                    try {
                        interTimer = setInterval(() => {
                            if (dialogueItem.index + 1 > dialogue.length) {
                                om.sendSinlgMessage('fin')
                                // 剧情结束清除缓存
                                clearDialogueStorage()
                                clearSession()
                                clearInterval(interTimer)
                                return
                            }
                            let item = dialogue[dialogueItem.index]
                            om.sendSinlgMessage(item.name ? `${item.name}：${item.dialog}` : item.dialog)
                            dialogueItem.index++
                        }, 5000)
                    } catch (error) {
                        console.log(error)
                        om.sendSinlgMessage('未知错误，已关闭此次操作！')
                        clearDialogueStorage()
                        clearSession()
                        clearInterval(interTimer)
                    }
                }
                break
            case 2:
                om.sendSinlgMessage('已结束本次剧情模拟。')
                clearInterval(interTimer)
                clearDialogueStorage()
                clearSession()

                break
            default:
                break
        }
        return
    }
    switch (parseInt(om.msg)) {
        case 1:
            if (dialogueItem.time) clearTimeout(dialogueItem.time)
            let dialogue = dialogueItem.dialogue
            if (dialogue && dialogue instanceof Array && dialogue.length > 0) {
                try {
                    if (dialogueItem.index + 1 > dialogue.length) {
                        om.sendSinlgMessage('fin')
                        // 剧情结束清除缓存
                        clearDialogueStorage()
                        clearSession()
                        return
                    }
                    dialogueItem.time = thisTimeout(60000, '超时，已结束本次操作。')
                    let item = dialogue[dialogueItem.index]
                    om.sendSinlgMessage(item.name ? `${item.name}：${item.dialog}` : item.dialog)
                    dialogueItem.index++

                } catch (error) {
                    console.log(error)
                    om.sendSinlgMessage('未知错误，已关闭此次操作！')
                    clearDialogueStorage()
                    clearSession()
                }
            }
            else {
                return
            }
            break
        case 2:
            if (dialogueItem.time) clearTimeout(dialogueItem.time)
            om.sendSinlgMessage('已结束本次剧情模拟。')
            clearDialogueStorage()
            clearSession()
            break
        default:
            break
    }

}

// 方舟剧情模块清除缓存
function clearDialogueStorage() {
    if (middle.dialogueStorage.findIndex(p => p.group == om.group) != -1) {
        let index = middle.dialogueStorage.findIndex(p => p.group == om.group)
        middle.dialogueStorage.splice(index, 1)
    }
}

// 神罚系统对话
function holyPressure() {
    // 删除
    const msgChain = om.msg.split(' ')
    if (msgChain[0] == '删除') {
        if (msgChain.length > 1 && holy_pressure_data[msgChain[1]]) {
            delete holy_pressure_data[msgChain[1]]
        }
        else {
            om.sendSinlgMessage('格式错误，请重新录入。')
            return
        }
    }
    else {
        om.sendSinlgMessage('正在校验中...')
        // 这里需要校验规则，暂时忽略
        om.sendSinlgMessage(`校验成功，神罚对象QQ：${om.msg}，正在将神罚对象录入系统...`)
        holy_pressure_data[om.msg] = om.msg
    }
    const dir = path.join(__dirname, '../data/holyPressureData.json')

    fs.writeFile(dir, JSON.stringify(holy_pressure_data), 'utf8', (err) => {
        om.sendSinlgMessage('修改成功，神罚系统已更新。')
        clearSession()
    })
}

// 清除会话缓存
function clearSession() {
    if (middle.sessions.findIndex(p => p.session == `${om.group}_${om.qq}`) != -1) {
        let index = middle.sessions.findIndex(p => p.session == `${om.group}_${om.qq}`)
        middle.sessions.splice(index, 1)
    }
}

// 超时处理
function thisTimeout(time, msg) {
    return setTimeout(() => {
        clearDialogueStorage()
        clearSession()
        om.sendGroupMessage(om.sendATGroup(msg))
    }, time)
}

function submit(defaults) {
    om = new Oumirai(defaults)
    // om = new om(order, group, msgFormat, qq)
    eval(defaults.order.func + '()')
}

module.exports = submit